import * as THREE from 'three'

/**
 * Three.js WebGLRenderTarget 调试工具,将其显示到一个canvas画布上。
 */
export class RenderTargetTool {

  /**
   * @param {*} options
   * @param {string} options.canvasClassName 渲染canvas的样式类名
   */
  constructor(options) {
    this._canvas = document.querySelector(options.canvasClassName)
    this._captureBuffer = {}
  }

  _resize(width, height) {
    const size = 4 * width * height;
    if(this._captureBuffer.length !== size) {
      this._captureBuffer = new Uint8Array(size)
    }
  }

  /**
   * 将渲染目标的内容渲染到 canvas 上
   * @param {THREE.WebGL1Renderer} renderer 渲染器
   * @param {THREE.WebGLRenderTarget} renderTarget 渲染目标
   */
  renderToCanvas(renderer, renderTarget) {
    const {width, height} = renderTarget;
    this._resize(width, height)

    renderer.readRenderTargetPixels(renderTarget, 0, 0, width, height, this._captureBuffer);

    this._canvas.width = width;
    this._canvas.height = height;

    const dataBuffer = new Uint8ClampedArray(this._captureBuffer.buffer)

    const ctx = this._canvas.getContext("2d");
    const imageData = ctx.createImageData(width, height);
    imageData.data.set(dataBuffer)
    ctx.putImageData(imageData, 0, 0)
  }
}
